package com.gb.models.user.service;

import com.gb.models.user.dao.SysUserDao;
import com.gb.models.user.dao.SysUserTokenDao;
import com.gb.models.user.model.SysUserEntity;
import com.gb.models.user.model.SysUserTokenEntity;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SysUserTokenService {

	//12小时后过期
	private final static int EXPIRE = 3600 * 12;

	@Resource
	private SysUserTokenDao userTokenDao;
	
	public SysUserTokenEntity queryByUserId(Long userId) {
		return userTokenDao.selectByUserId(userId);
	}

	public int save(SysUserTokenEntity entity) {
		return userTokenDao.save(entity);
	}

	public int update(SysUserTokenEntity entity) {
		return userTokenDao.update(entity);
	}


	public String updateToken(Long userId, String userName){
		//生成一个token
		String token = Jwts.builder().setSubject(userName).claim("roles", "user").setIssuedAt(new Date())
				.signWith(SignatureAlgorithm.HS256, "base64EncodedSecretKey").compact();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		SysUserTokenEntity tokenEntity = queryByUserId(userId);
		if(tokenEntity == null){
			tokenEntity = new SysUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			//保存token
			save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			//更新token
			update(tokenEntity);
		}
		return token;
	}
}
